//
//  ViewController.swift
//  lottieTest
//
//  Created by Pro on 2022/6/27.
//

import UIKit
import Lottie

class ViewController: UIViewController {
    var animationView: AnimationView?
    override func viewDidLoad() {
        super.viewDidLoad()
  
        //打开注释展示本地coffee.json文件的效果
//        self.displayLocalJsonFileWithName(string: "coffee")
        
        //打开注释，展示远程地址下zy_lottie_live.json文件的效果
        self.displayUrlJsonFileWithUrl(urlString: "https://elinknft.oss-cn-hangzhou.aliyuncs.com/lottie/zy_lottie_live.json")
        
    }
    //展示本地的.json文件
    func displayLocalJsonFileWithName(string:String) {
        //初始化
        animationView = .init(name: string)
//        设置frame
        animationView!.frame = view.bounds
//        设置填充方式
        animationView!.contentMode = .scaleAspectFit
        animationView!.animationSpeed = 0.5
        view.addSubview(animationView!)
//        循环播放
        animationView!.loopMode = LottieLoopMode.loop
        animationView!.play()
        animationView?.backgroundBehavior = .pauseAndRestore

    }
    
    //展示网络地址的json文件
    func displayUrlJsonFileWithUrl(urlString:String) {
        let url:URL = URL.init(string: urlString)!

        animationView = .init(url: url, imageProvider: nil, closure: { error in
                self.startDisplay()
        }, animationCache: nil)
        view.backgroundColor = .blue
    }
    
    
    //远程资源下的json文件需要执行完下载之后才能开始动画
    func startDisplay(){
        animationView!.frame = view.bounds
        // 3. Set animation content mode
        animationView!.contentMode = .scaleAspectFit
        // 4. Set animation loop mode
        // 5. Adjust animation speed
        animationView!.animationSpeed = 0.5
        view.addSubview(animationView!)
        // 6. Play animation
        animationView!.loopMode = LottieLoopMode.loop
        animationView!.play()
        animationView?.backgroundBehavior = .pauseAndRestore

    }
    
    
    
}
